package com.example.security.config;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.authentication.builders.*;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.*;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableMethodSecurity
public class WebSecurityConfig {

//	@Bean
//	public UserDetailsService userDetailsService() {
//		// 创建基于内存的用户信息管理器
//		InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//		// 创建userDetails对象，用于管理用户信息
//		manager.createUser(User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build());
//		return manager;
//	}


//	@Bean
//	public UserDetailsService userDetailsService() {
//		// 创建数据库的用户信息管理器
//		DBUserDetailsManager manager = new DBUserDetailsManager();
//		return manager;
//	}

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        //authorizeRequests()：开启授权保护
        http.authorizeRequests(authorize -> authorize
//                .requestMatchers("user/list").hasAnyAuthority("USER_LIST") // 配置用户列表接口的权限
//                .requestMatchers("user/add").hasAnyAuthority("USER_ADD") // 配置用户添加接口的权限
//                .requestMatchers("/user/**").hasRole("ADMIN") // 配置用户接口下的角色
                .anyRequest() //对所有请求开启授权保护
                .authenticated()); //已认证请求会自动被授权
//                .formLogin(withDefaults())//表单授权方式 使用默认的登录页面和登出页面


        http.formLogin(form -> {
            form.loginPage("/login").permitAll()  // 自定义登录页面 无需授权即可访问当前页面
                    .usernameParameter("username") // 登录表单中用户名的参数名
                    .passwordParameter("password") // 登录表单中用户名密码的参数名
                    .failureForwardUrl("/login?error") // 登录失败跳转页面
                    .successHandler(new MyAuthenticationSuccessHandler()) // 登录成功时的处理
                    .failureHandler(new MyAuthenticationFailureHandler()); // 登录失败的
//            .httpBasic(withDefaults());//基本授权方式
        });
//
//        注销登录处理
        http.logout(
                logout -> logout.
                        logoutSuccessHandler(new MyLogoutSuccessHandler()));
//        错误处理
        http.exceptionHandling(exception -> {
//            请求未认证的接口
            exception.authenticationEntryPoint(new MyAuthenticationEntryPoint());
//            请求未授权的接口
            exception.accessDeniedHandler(new MyAccessDeniedHandler());
        });
        //跨域
        http.cors(withDefaults());
        //会话管理
        http.sessionManagement(session -> {
            session
                    .maximumSessions(1) // 最大会话数 后登录的账号会使先登录的账号失效
                    .expiredSessionStrategy(new MySessionInformationExpiredStrategy());
        });

        //关闭csrf攻击防御
        http.csrf((csrf) -> {
            csrf.disable();
        });
        return http.build();

    }
}